<template>
  <div class="login-setting">
    <el-form ref="userInfoForm" :model="userInfoForm" :rules="rules" label-width="300px" style="width:50%;margin-top:40px">
      <el-form-item label="姓 名：" prop="username">
        <el-input v-model="userInfoForm.username" />
      </el-form-item>
      <el-form-item label="密 码：" prop="password">
        <el-input v-model="userInfoForm.password" disabled type="password" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateInfo">更新</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { getUserDetailById, saveUserDetailById } from '@/api/user'
export default {
  data() {
    return {
      userInfoForm: {
        username: '',
        password: ''
      },
      rules: {
        username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
        password: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getUserDetail()
  },
  methods: {
    async getUserDetail() {
      const res = await getUserDetailById(this.$route.params.id)
      const { username, password } = res.data
      this.userInfoForm = { username, password }
    },
    updateInfo() {
      this.$refs.userInfoForm.validate(async valid => {
        if (!valid) return
        const id = {
          id: this.$route.params.id
        }
        try {
          await saveUserDetailById({ ...this.userInfoForm, ...id })
          this.$message.success('更新信息成功！')
        } catch (err) {
          console.log('saveUserDetailById', err)
          this.$message.error('修改失败')
        }
      })
    }
  }
}
</script>
